import React, { Component } from 'react';
import ReactDOM from 'react-dom';
import { base, ajax, toast, createPage } from 'nc-lightapp-front';
import { initTemplate, afterEvent, searchClick } from './events';
import requestApi from './requestApi'
import './index.less';
import { setSearch } from 'ssccommon/utils/setComponentUsed'

window.pageCode = {
    searchPage: '20110ETLB_cjk'
};
window.cjkAreaCode = {
    searchArea: '20110ETLB',
    billsArea: 'head',
    bodysArea: 'jk_busitem'
};

export default class Cjk extends Component {
    constructor(props) {
        super(props);
        setSearch(props, window.cjkAreaCode.searchArea)
        this.state = {
            showCJKModal: true,
        }

        let { form, button, table, editTable, search } = this.props;
        let { setSearchValue, setSearchValByField, getAllSearchData } = search;
        this.setSearchValByField = setSearchValByField;//设置查询区某个字段值
        this.getAllSearchData = getAllSearchData;//获取查询区所有字段数据

        this.isError = false; //转单编辑后字段是否通过验证
        // if (this.props.showCJKModal) {
        //     initTemplate.call(this, props);
        // }

    }
    setTransferBtnDisabled(flag) {
        //设置“冲借款”按钮是否可用
        let btnObj = document.querySelector('.area-right .main-button');
        if (flag == true) {
            btnObj&&btnObj.setAttribute('disabled', true);
        } else {
            btnObj&&btnObj.removeAttribute('disabled');
        }

    }

    componentDidMount() {
        //设置“冲借款”按钮在不勾选任何数据的时候也可用，添加监听 begin
        /* let that = this;
        var time = setInterval(() => {
            let btnObj = document.querySelector('.area-right .main-button');
            if (btnObj) {
                clearInterval(time);
                btnObj.addEventListener('click', function () {
                    //判断是否有已选的条目，有就直接return， 无则继续执行逻辑
                    let selectdata = that.props.transferTable.getTransferTableSelectedValue()
                    if (selectdata != undefined && selectdata.head != undefined && selectdata.head.length > 0) {
                        return;
                    }
                    window.pageCjkClick(null);
                })
            }
        }, 300) */
        //end 
        if (this.props.showCJKModal) {
            initTemplate.call(this, this.props);
        }
        this.props.transferTable.setTransferTableValue(window.cjkAreaCode.billsArea, window.cjkAreaCode.bodysArea, [], 'pk_jkbx', 'pk_busitem');
    }

    render() {
        let { form, button, table, editTable, search, transferTable } = this.props;
        let { NCCreateSearch } = search;
        let { createButton } = button;
        let { createEditTable } = editTable;

        let { createTransferTable } = transferTable;
        let tradetype = this.props.getUrlParam("tradetype");
        let multiLang = this.props.MutiInit.getIntl(2011); //this.moduleId
        return (
            // "201102BCLF-0009": "借款单",
            <div className="nc-single-table" style = {{backgroundColor:'#e0e4ec'}}>
                {/*
            <div className="title">{multiLang && multiLang.get('201102BCLF-0009')}</div>
                <div className="header">

                </div>
                <div className="content-wrap">
                    <div className="bar">

                    </div>
                </div>

            */}

                <div className="nc-singleTable-search-area">
                    {NCCreateSearch(
                        window.cjkAreaCode.searchArea,//模块id
                        {

                            clickPlanEve: searchClick.bind(this),//点击高级面板中的查询方案事件
                            clickSearchBtn: searchClick.bind(this),//   点击按钮事件
                            defaultConditionsNum: 1, //默认显示几个查询条件
                            onAfterEvent: afterEvent()//编辑后事件
                        }
                    )}
                </div>
                <div className="nc-singleTable-table-area" id="transferCjk">
                    {createTransferTable(
                        {
                            editStatus: true,
                            headTableId: window.cjkAreaCode.billsArea,//表格组件id
                            bodyTableId: window.cjkAreaCode.bodysArea,//子表模板id
                            fullTableId: window.cjkAreaCode.bodysArea,//主子拉平模板id
                            //点击加号展开，设置表格数据
                            transferBtnText: multiLang && multiLang.get("201102BCLF-0002"), //转单按钮显示文字
                            containerSelector: '#transferCjk', //容器的选择器 必须唯一,用于设置底部已选区域宽度
                            cacheItem: ['cjkybje', 'pk_jkbx', 'pk_busitem', 'hkybje', 'djlxbm', 'djbh', 'bzbm', 'pk_org',
                                'pk_group', 'jkbxr', 'ybje', 'ybye', 'yjye', 'zfybje', 'szxmid', 'deptid', 'jobid', 'pk_payorg'], //缓存字段
                            editableItem: ['cjkybje', 'hkybje'], //可编辑字段
                            generateKeys: {
                                head: ['cjkybje', 'pk_jkbx', 'pk_busitem', 'hkybje', 'djlxbm', 'djbh', 'bzbm', 'pk_org',
                                    'pk_group', 'jkbxr', 'ybje', 'ybye', 'yjye', 'zfybje', 'szxmid', 'deptid', 'jobid', 'pk_payorg']
                            },
                            afterEvent: (attrcode, value, record, index, oldvalue) => {
                                console.log('编辑后事件', attrcode, value, record, index, oldvalue);

                                switch (attrcode) {
                                    case 'cjkybje':
                                        // "201102BCLF-0010": "冲借款金额不能大于借款余额",
                                        if (record.yjye && record.yjye.value && parseFloat(value) > parseFloat(record.yjye.value)) {
                                            toast({ content: multiLang && multiLang.get('201102BCLF-0010'), color: 'danger' });
                                            this.isError = true;
                                            record.cjkybje = {display:parseFloat(oldvalue), value: parseFloat(oldvalue)} 
                                            this.props.transferTable.setRowDataByIndex('head', record, index);
                                            return
                                        } else {
                                            this.isError = false;
                                            let pk_bzbm = record.bzbm.value;
                                            if (window.bxjeMap.has(pk_bzbm)) {
                                                let selectrow = this.props.transferTable.getTransferTableSelectedValue();
                                                let isSelect = false;
                                                if (selectrow.head && selectrow.head.length > 0) {
                                                    selectrow.head.forEach((item) => {
                                                        if (item.head.head.rows[0].values.pk_jkbx.value == record.pk_jkbx.value) {//此行为选中状态
                                                            isSelect = true;
                                                        }
                                                    });
                                                }
                                                let scala = record.yjye&&record.yjye.scale||'4'//value.split('.')[1] && record.yjye.value.split('.')[1].length > 0 ? record.yjye.value.split('.')[1].length : 0;
                                                let bxye = parseFloat(window.bxjeMap.get(pk_bzbm));
                                                //报销金额 + 原冲销金额 - 还款金额 = 报销余额
                                                let bxye_old = parseFloat(window.bxjeMap.get(pk_bzbm)) + parseFloat(oldvalue) - parseFloat(record['hkybje'].value);//重新计算报销余额，重要
                                                
                                                if (isSelect) {//选中状态
                                                    //冲借款金>可报销金额 && 冲借款金额 <= 借款余额  计算还款金额
                                                    if(parseFloat(value) > parseFloat(bxye_old) && parseFloat(value) <= parseFloat(record.yjye.value)) {
                                                        const vv = (parseFloat(value)-parseFloat(bxye_old)).toFixed(scala)
                                                        record['hkybje'] = {display: vv, value: vv, scale:scala};
                                                    } else {
                                                        //重新计算借款余额
                                                        record['hkybje'] = {display: (0).toFixed(scala), value: (0).toFixed(scala), scale:scala};
                                                    }
                                                    record.cjkybje.scale = scala;
                                                    window.bxjeMap.delete(pk_bzbm);
                                                    window.bxjeMap.set(pk_bzbm, bxye_old - parseFloat(record.cjkybje.value) + parseFloat(record['hkybje'].value));//重置报销余额
                                                } else {//非选中状态，设置还款金额=0
                                                    record['hkybje'] = {display:"0.00", value:"0.00", scale: scala};
                                                }
                                                record.cjkybje = {display:value, scale:scala, value}
                                                this.props.transferTable.setRowDataByIndex('head', record, index);
                                               
                                                let hkybje_sethead =0.00;
                                                let selectrowbody = this.props.transferTable.getTransferTableSelectedValue();
                                                if (selectrowbody.head && selectrowbody.head.length > 0) {
                                                    selectrowbody.head.forEach((item) => {
                                                       if (item.head.head.rows[0].values.pk_jkbx.value == record.pk_jkbx.value) {
                                                           if (item.body.jk_busitem) {
                                                               for (let num = 0; num < item.body.jk_busitem.rows.length; num++) {
                                                                   if (
                                                                       item.body.jk_busitem.rows[num].values.hkybje &&
                                                                       item.body.jk_busitem.rows[num].values.hkybje.value != 'NaN'
                                                                   ) {
                                                                       hkybje_sethead += parseFloat(
                                                                           item.body.jk_busitem.rows[num].values.hkybje.value
                                                                       );
                                                                   }
                                                               }
                                                           }
                                                       }
                                                       let sum = 0
                                                       item.body.jk_busitem.rows.forEach(row => {
                                                           sum += Number(row.values.cjkybje.value)
                                                       })
                                                       let row = null
                                                       if (row = item.body.jk_busitem.rows[0]) {
                                                           this.props.transferTable.updateHeadRowByKey('head', { cjkybje: {display:sum, scale:scala, value: sum }, hkybje: { display:String(hkybje_sethead.toFixed(scala)), scale:scala, value: String(hkybje_sethead.toFixed(scala)) } }, row.values.parentRowId || row.values.headKey);
                                                       }
                                                    });
                                                } else {
                                                    this.props.transferTable.updateHeadRowByKey('head', { cjkybje: { display: 0, scale:scala, value: 0 }, hkybje:{display: 0, scale:scala, value:0} }, record.parentRowId || record.headKey);
                                                }
                                                if (hkybje_sethead == 0) {
                                                    hkybje_sethead = '0.00';
                                                }
                                            }
                                        }
                                        break;
                                }
                            }, //编辑后事件 
                            onTransferBtnClick: (ids) => {//点击转单按钮钩子函数
                                if (this.isError) {
                                    toast({ content: multiLang && multiLang.get('201102BCLF-0011'), color: 'danger' });
                                } else {
                                    window.pageCjkClick(ids);
                                }
                            },
                            onCheckedChange: (flag, record, index, bodys) => {
                                this.setTransferBtnDisabled(false);
                                let datas = [];
                                //选中子表
                                if (record.parentRowId) {
                                    datas[0] = record;
                                } else if (bodys && bodys.length > 0) {
                                    datas = bodys;
                                }
                                if (flag == true) {
                                    // bzbm: 币种  cjkybje: 冲借款原币金额  
                                    datas.forEach((data) => {
                                        //币种编码
                                        let pk_bzbm = data.bzbm.value;
                                        if (window.bxjeMap.has(pk_bzbm)) {
                                            // bxye 按照币种获取报销金额  yjye: 借款余额
                                            let bxye = parseFloat(window.bxjeMap.get(pk_bzbm));
                                            let scala = data.yjye&&data.yjye.scale || '4' //value.split('.')[1]&&data.yjye.value.split('.')[1].length > 0 ? data.yjye.value.split('.')[1].length : 0;
                                            if (bxye > 0) {
                                                //报销金额大于借款余额，冲借款金额=借款余额,否则冲借款金额=报销金额
                                                if (bxye - parseFloat(data.yjye.value) > 0) {
                                                    data['cjkybje'] =  {display:data['yjye'].value, value:data['yjye'].value, scale:scala} //data['yjye'].value;
                                                } else {
                                                    data['cjkybje'] = {display:bxye.toFixed(scala), scale:scala, value: bxye.toFixed(scala)};
                                                }
                                                let bxye_new = (bxye - parseFloat(data['cjkybje'].value) + parseFloat(data['hkybje'].value)).toFixed(scala);//重新计算报销余额，重要
                                                window.bxjeMap.delete(pk_bzbm);
                                                window.bxjeMap.set(pk_bzbm, bxye_new);//重置报销余额
                                            } 
                                            this.props.transferTable.setRowDataByIndex('head', data, data.rowIndex);
                                        } else {
                                            // "201102BCLF-0012": "不存在当前币种的报销记录，不能冲借款",
                                            toast({ content: multiLang && multiLang.get('201102BCLF-0012'), color: 'danger' });
                                        }
                                    });

                                } else if (flag == false) {
                                    datas.forEach((data) => {
                                        let scala = data.yjye&&data.yjye.scale||'4'//value.split('.')[1]&&data.yjye.value.split('.')[1].length > 0 ? data.yjye.value.split('.')[1].length : 0;
                                        let bzbm = data.bzbm.value;
                                        let bxye_new_cancle = parseFloat(window.bxjeMap.get(bzbm)) + parseFloat(data.cjkybje.value) - parseFloat(data.hkybje.value);//重新计算报销余额，重要
                                        window.bxjeMap.delete(bzbm);
                                        window.bxjeMap.set(bzbm, bxye_new_cancle.toFixed(2));//重置报销余额
                                        data['cjkybje'] = {display:parseFloat("0.00").toFixed(scala), scale:scala ,value: parseFloat("0.00").toFixed(scala)} // parseFloat("0.00").toFixed(scala);
                                        data['hkybje'] = {display:parseFloat("0.00").toFixed(scala), scale:scala ,value: parseFloat("0.00").toFixed(scala)} //parseFloat("0.00").toFixed(scala);
                                        this.props.transferTable.setRowDataByIndex('head', data, data.rowIndex);
                                    });
                                }


                                let hkybje_sethead =0.00;
                                let scale=record.amount&&record.amount.scale || '4';
                                let selectrowbody = this.props.transferTable.getTransferTableSelectedValue();
                                if (selectrowbody.head && selectrowbody.head.length > 0) {
                                    selectrowbody.head.forEach((item) => {
                                       if (
                                           item.head.head.rows[0].values.pk_jkbx.value ===
                                           ((record.pk_jkbx && record.pk_jkbx.value) || '')
                                       ) {
                                           if (item.body.jk_busitem) {
                                               for (let num = 0; num < item.body.jk_busitem.rows.length; num++) {
                                                   if (
                                                       item.body.jk_busitem.rows[num].values.hkybje &&
                                                       item.body.jk_busitem.rows[num].values.hkybje.value != 'NaN'
                                                   ) {
                                                       hkybje_sethead += parseFloat(
                                                           item.body.jk_busitem.rows[num].values.hkybje.value
                                                       );
                                                   }
                                               }
                                           }
                                       }
                                       let sum = 0
                                        item.body.jk_busitem.rows.forEach(row => {
                                            sum += Number(row.values.cjkybje.value)
                                        })
                                        let row = null
                                        if (row = item.body.jk_busitem.rows[0]) {
                                            this.props.transferTable.updateHeadRowByKey('head', { cjkybje: {display:String(sum.toFixed(scale)), scale, value: String(sum.toFixed(scale)) } }, row.values.parentRowId || row.values.headKey);
                                        }
                                    });
                                } else {
                                    datas.forEach((data) => {
                                        this.props.transferTable.updateHeadRowByKey('head', { cjkybje: {display:'0', scale, value: '0' } }, record.parentRowId || record.headKey);
                                    });
                                }
                                this.props.transferTable.updateHeadRowByKey('head', { "hkybje": { display: String(hkybje_sethead.toFixed(scale)), scale, value: String(hkybje_sethead.toFixed(scale)) } }, record.parentRowId || record.headKey);
                               
                            },
                            onChangeViewClick: () => {//点击切换视图钩子函数
                                if (!this.props.meta.getMeta()[window.cjkAreaCode.bodysArea]) {
                                    initTemplate.call(this, this.props); //加载主子拉平模板
                                }
                                this.props.transferTable.changeViewType(this.headTableId);
                            }
                        })}
                </div>
            </div>

        )
    }
}

Cjk = createPage({
    mutiLangCode: '2011'
})(Cjk);

ReactDOM.render(<Cjk />, document.querySelector('#app'))